#!/bin/bash

includeList=
testList=
bin=test_main.qg
cbin=./main_opt
dbin=./main_dbg
binaries="$dbin ./main_opt"
valGrind=

binBody=

if [ ! -e ./default.qg ]; then
  touch default.qg;
else
  if ! ./main_opt -compile &> /dev/null; then
     echo 'Error: Could not compile default.qg module.' > /dev/stderr;
     echo 'Please check file for errors and rerun test.' > /dev/stderr;
     exit 1;
  fi
fi

# generate test harness list
for file in test_*.qg; do
 if [ "$file" != "${bin}" ]; then
  if ${cbin} -namelist $file -compile &> /dev/null; then
    includeList=$file' '$includeList
  else
    echo Error compiling $file. > /dev/stderr;
    ${cbin} -namelist $file -compile &> /dev/stderr;
    echo Skipping all tests in $file because of compilation errors..... > /dev/stderr;
  fi
 fi
done

# generate header
printf ' // *************************************************************\n' > ${bin}
printf ' // \n' >> ${bin}
printf ' // Autogenerated script file for BAT \n' >> ${bin}
printf ' // \n\n' >> ${bin}


# output the include list
for testFile in $includeList; do
    printf 'INCLUDE "%s";\n' "$testFile" >> ${bin}
done


# generate the script header
printf 'SCRIPT {\n\n' >> ${bin}
printf '\t DECLARE bool status = true; \n' >> ${bin}

# generate test list
for testFile in $includeList; do
   testList=$(${cbin} -namelist $testFile -printuserfuncs | grep "bool\s*test_\w*()" | sed 's/bool\s*//')
   for test in $testList; do
       printf '\t// Testpoint %s in file %s.\n' $test $testFile >> ${bin}
       printf '\t status = status && %s;\n' $test >> ${bin}
       printf '\t if( ! status ) then;\n' >> ${bin}
       printf '\t    printf("Test failure at test point %%s in file %%s.\\n", "%s", "%s");\n' $test $testFile >> ${bin}
       printf '\t endif;\n\n' >> ${bin}
   done
done

# generte script footer
printf '\t if( ! status ) then;\n' >> ${bin}
printf '\t     abort(1);\n' >> ${bin}
printf '\t endif;\n' >> ${bin}
printf '\n};\n' >> ${bin}

for binary in ${binaries}; do
if ! ${binary} -runscript ${bin}; then
   echo 'Tests failed for binary: '${binary};
else
   echo 'All tests passed for binary: '${binary};
fi
done

# Running tests through valgrind
echo 'Running valgrind tests on debug version.'
valgrind -q ${dbin} -runscript ${bin} 
